<script lang="ts">
  let show = true;
  let count = 200000;
  let time = 0;
  let color = "red";

  const onToggle = () => {
    show = !show;

    if (!show) return;
    let t = performance.now();
    let timer: any;
    timer = setInterval(() => {
      if (document.getElementById("box_" + (count - 1))) {
        time = Math.floor(performance.now() - t);
        timer && clearInterval(timer);
      }
    }, 50);
  };

  const onBg = (c: string) => {
    color = c;
    let t = performance.now();
    const dom = document.getElementById("box_" + (count - 1));
    let timer: any;
    timer = setInterval(() => {
      if (dom?.style.backgroundColor == c) {
        time = Math.floor(performance.now() - t);
        timer && clearInterval(timer);
      }
    }, 50);
  };
</script>

<main>
  <div>
    显示：{show} &nbsp;&nbsp; len: {count} &nbsp;&nbsp; time: {time}ms
    <br />
    <button on:click={onToggle}>显示/隐藏</button>
    &nbsp;&nbsp;
    <button on:click={() => onBg("red")}>红色</button>
    &nbsp;&nbsp;
    <button on:click={() => onBg("green")}>绿色</button>
    <hr />
    <div class="main">
      {#if show}
        {#each Array(count) as _, i}
          <span
            class="box"
            id={"box_" + i}
            style={`background-color: ${color}`}
          />
        {/each}
      {/if}
    </div>
  </div>
</main>

<style>
  .main {
    width: 100%;
    max-height: 90vh;
    overflow: auto;
  }

  .box {
    width: 20px;
    height: 20px;
    display: inline-block;
    text-align: center;
    margin-right: 5px;
    margin-bottom: 5px;
    cursor: pointer;
  }
</style>
